package com.zhentao.config;

import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.MessageChatMemoryAdvisor;
import org.springframework.ai.chat.client.advisor.SimpleLoggerAdvisor;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.memory.ChatMemoryRepository;
import org.springframework.ai.chat.memory.MessageWindowChatMemory;
import org.springframework.ai.chat.memory.repository.jdbc.JdbcChatMemoryRepository;
import org.springframework.ai.chat.model.ChatModel;
import org.springframework.ai.chat.prompt.SystemPromptTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.jdbc.core.JdbcTemplate;
import reactor.core.scheduler.Schedulers;

import javax.sql.DataSource;

@Configuration
public class AiConfig {


    @Value("classpath:/prompts/system-message.st")
    private Resource systemResource;

    @Autowired
    private RedisChatMemory redisChatMemory;


    @Bean
    public ChatClient deepSeekChatClient(ChatModel chatModel) {
        SystemPromptTemplate systemPromptTemplate = new SystemPromptTemplate(systemResource);
        return ChatClient.builder(chatModel)
                .defaultSystem(systemPromptTemplate.render())
                .defaultAdvisors(MessageChatMemoryAdvisor.builder(redisChatMemory) // 👈 使用 builder
                        .conversationId("default") // 可选，默认值
                        .order(-2147482648)         // 默认顺序，可不写
                        .scheduler(Schedulers.boundedElastic()) // 推荐使用 boundedElastic
                        .build())
                .build();
    }
    @Bean
    public ChatMemory chatMemory() {
        // 默认存储最近的 10 条消息
        return MessageWindowChatMemory.builder().maxMessages(10).build();
    }

    @Bean
    public MessageChatMemoryAdvisor chatMemoryAdvisor(ChatMemory chatMemory) {
        return MessageChatMemoryAdvisor.builder(chatMemory).build();
    }

    @Bean
    public SimpleLoggerAdvisor simpleLoggerAdvisor() {
        return new SimpleLoggerAdvisor();
    }


    @Bean
    public ChatMemoryRepository chatMemoryRepository(DataSource dataSource) {
        JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
        return JdbcChatMemoryRepository.builder().jdbcTemplate(jdbcTemplate).build();
    }


}
